package com.ciwong.epaper.modules.wordlist.ui;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.wordlist.WordListReadActivity;
import com.ciwong.epaper.modules.wordlist.bean.PageListBean;
import com.ciwong.epaper.modules.wordlist.bean.WordDownloadInfo;
import com.ciwong.epaper.modules.wordlist.bean.WorkBookBean;
import com.ciwong.epaper.modules.wordlist.dao.WorkBookDao;
import com.ciwong.epaper.modules.wordlist.util.WordBookDownload;
import com.ciwong.epaper.modules.wordlist.widget.WordBookWordDetailView;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by keepon on 2018/3/29.
 */

public class WordBookWordDetailActivity extends BaseActivity implements View.OnClickListener {

    private WordBookWordDetailView mExerciseBookWordDetailView;
    private TextView mTvNextWord, mTvPreWord;
    public static final int REQUEST_FOR_WORD_LIST = 1001;
    private int mCurPage = 1;
    private int mPageSize = 20;
    List<PageListBean> mDataList = new ArrayList<>();
    private int mCurrentItem = 0;
    private String mScoreRange = "0,100";//被查询单词范围（默认 全部）
    private boolean isTheLastPage = false;
    private EApplication application;
    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    @Override
    protected void preCreate() {
        super.preCreate();
        Intent intent = getIntent();
        if (intent != null) {
            mDataList = (List<PageListBean>) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
            mCurrentItem = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
            mScoreRange = intent.getStringExtra(IntentFlag.INTENT_FLAG_STR);
            mCurPage = intent.getIntExtra(IntentFlag.INTENT_FLAG_CURRENT_PAGE, 1);
        }
    }

    @Override
    protected int setView() {
        return R.layout.activity_work_detail_exercise_book;
    }

    @Override
    protected void findViews() {
        mExerciseBookWordDetailView = findViewById(R.id.exercise_book_word_detail_view);
        mTvNextWord = findViewById(R.id.tv_next_word);
        mTvPreWord = findViewById(R.id.tv_pre_word);
    }

    @Override
    protected void initEvent() {
        mTvNextWord.setOnClickListener(this);
        mTvPreWord.setOnClickListener(this);
        mExerciseBookWordDetailView.setOnPageSelectChangeListener(new WordBookWordDetailView.OnPageSelectChangeListener() {
            @Override
            public void onPageSelected(int index) {
                if (mDataList.size() > 0 && index == mDataList.size() - 1) {
                    getNetMsgListByID();
                }
                mCurrentItem = index;

                if (index == 0) {
                    mTvPreWord.setEnabled(false);
                    mTvPreWord.setBackgroundResource(R.color.color_btn_disable);
                } else {
                    mTvPreWord.setEnabled(true);
                    mTvPreWord.setBackgroundResource(R.drawable.btn_light_green_bg_selector);
                }

                if (mCurrentItem == mDataList.size() - 1 && isTheLastPage) {
                    mTvNextWord.setEnabled(false);
                    mTvNextWord.setBackgroundResource(R.color.color_btn_disable);
                } else {
                    mTvNextWord.setEnabled(true);
                    mTvNextWord.setBackgroundResource(R.drawable.btn_light_green_bg_selector);
                }


                ToastUtil.INSTANCE.cancelToast();

            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (mCurrentItem == position && positionOffset >= 0.3) {
                    if (AudioPlayer.getInstance().isPlaying()) {
                        AudioPlayer.getInstance().stop();
                    }
                } else if (mCurrentItem == position + 1 && positionOffset <= 0.7) {
                    if (AudioPlayer.getInstance().isPlaying()) {
                        AudioPlayer.getInstance().stop();
                    }
                }
            }
        });
    }

    @Override
    protected void init() {
        application = (EApplication) getApplication();
        if (application != null) {
            //服务是否过期
            serviceExpired = application.isServiceExpired();
        }
        if (mCurrentItem == 0) {
            mTvPreWord.setEnabled(false);
            mTvPreWord.setBackgroundResource(R.color.color_btn_disable);
        }
    }

    @Override
    protected void loadData() {
        setTitleText("单词详情");
        mExerciseBookWordDetailView.setData(WordBookWordDetailActivity.this, mDataList, mCurrentItem, true, serviceExpired);
        PageListBean pageListBean = mDataList.get(mCurrentItem);
        WordDownloadInfo wordDownloadInfo = new WordDownloadInfo();
        wordDownloadInfo.setWord(pageListBean.getContent());
        wordDownloadInfo.setNativeAudio(true);
        wordDownloadInfo.setAudioUrl(pageListBean.getResource().getAudioUrl());
        File localAudioPath = WordBookDownload.getInstance().getLocalAudioPath(wordDownloadInfo);
        if (!localAudioPath.exists()) {
            //不存在的话下载原生音频
            wordDownloadInfo.setLocalPath(localAudioPath.getPath());
            WordBookDownload.getInstance().startTask(wordDownloadInfo);
        }

        WordDownloadInfo recordWordDownlaodInfo = new WordDownloadInfo();
        recordWordDownlaodInfo.setWord(pageListBean.getContent());
        recordWordDownlaodInfo.setNativeAudio(true);
        recordWordDownlaodInfo.setAudioUrl(pageListBean.getResource().getAudioUrl());
        File localAudioPath2 = WordBookDownload.getInstance().getLocalAudioPath(recordWordDownlaodInfo);
        if (!localAudioPath2.exists()) {
            //不存在的话下载录音音频
            recordWordDownlaodInfo.setLocalPath(localAudioPath2.getPath());
            WordBookDownload.getInstance().startTask(recordWordDownlaodInfo);
        }

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_next_word) {
            mExerciseBookWordDetailView.next();
        } else if (id == R.id.tv_pre_word) {
            mExerciseBookWordDetailView.pre();
        }

    }

    /**
     * 获取网络数据
     */
    private void getNetMsgListByID() {
        mCurPage++;
        WorkBookDao.getInstance().getWorkBookListFromNet(EApplication.BRAND_ID, getUserInfoBase().getUserId(), mCurPage, mPageSize, mScoreRange,
                new BaseExtCallBack(this) {
                    @Override
                    public void failed(Object data) {
                        super.failed(data);
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        if (errorCode == 17 || errorCode == 27) {
                            isTheLastPage = true;
                            if (mCurrentItem == mDataList.size() - 1 && isTheLastPage) {
                                mTvNextWord.setEnabled(false);
                                mTvNextWord.setBackgroundResource(R.color.color_btn_disable);
                            } else {
                                mTvNextWord.setEnabled(true);
                                mTvNextWord.setBackgroundResource(R.drawable.btn_light_green_bg_selector);
                            }
                            mCurPage--;
                        }
                    }

                    @Override
                    public void success(Object data) {
                        WorkBookBean workBookBean = (WorkBookBean) data;
                        List<PageListBean> pageList = workBookBean.getPageList();
                        if (pageList != null && pageList.size() > 0) {
                            mDataList.addAll(pageList);
                            mExerciseBookWordDetailView.setData(WordBookWordDetailActivity.this, pageList, mCurrentItem, false, serviceExpired);
                        } else {
                            isTheLastPage = true;
                            if (mCurrentItem == mDataList.size() - 1 && isTheLastPage) {
                                mTvNextWord.setEnabled(false);
                                mTvNextWord.setBackgroundResource(R.color.color_btn_disable);
                            } else {
                                mTvNextWord.setEnabled(true);
                                mTvNextWord.setBackgroundResource(R.drawable.btn_light_green_bg_selector);
                            }
                            mCurPage--;

                        }

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioPlayer.getInstance().release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == WordListReadActivity.REQUEST_CODE_FROM_WORD_LIST_DETAIL && data != null) {
                int score = data.getIntExtra(IntentFlag.INTENT_FLAG_ACTUAL_SCORE, -1);
                String evaluateResultString = data.getStringExtra(IntentFlag.INTENT_FLAG_EVALUATE_RESULT);
                if (score != -1) {
                    mDataList.get(mCurrentItem).getRecords().setScore(score);
                    if (EApplication.isSymbolColoration) {
                        mDataList.get(mCurrentItem).getRecords().setLines(evaluateResultString);
                    }
                    mExerciseBookWordDetailView.setData(WordBookWordDetailActivity.this, mDataList, mCurrentItem, true, serviceExpired);
                }

            }
        }
    }
}
